Date and Time Operations

The Get-Date cmdlet gets a DateTime object that represents the current date or a date that you specify. It can format the date and time in several Windows and UNIX formats. You can use Get-Date to generate a date or time character string, and then send the string to other cmdlets or programs

Commands

This command gets a DateTime object, but it displays only the date. It uses the -DisplayHint parameter to indicate that only the date is to be displayed

Get-Date -DisplayHint Date #output Tuesday, June 13, 2006

This command gets the current date and time and formats it in short-date and short-time format. It uses the .NET Framework "g" format specifier (General [short date and short time]) to specify the format.

Get-Date -Format g #output 6/13/2006 12:43 PM

This command gets the current date and time and formats it as specified by the command. In this case, the format includes the full year (%Y), the two-digit numeric month (%m), the date (%d), the full day of the week (%A), and the offset from UTC ("Zulu").

Get-Date -UFormat "%Y / %m / %d / %A / %Z" #output 2006 / 06 / 13 / Tuesday / -07

This command displays the day of the year for the current date. For example, December 31 is the 365th day of 2006, but it is the 366th day of 2000.

(Get-Date -Year 2000 -Month 12 -Day 31).DayOfYear #output 366

These commands tell you whether the current date and time are adjusted for daylight savings time in the current locale. The first command creates a variable named $a and then assigns the object retrieved by Get-Date to the $a variable. Then, it uses the IsDaylightSavingTime method on the object in $a. To see the properties and methods of the DateTime object, type: Get-Date | Get-Member

Second commands convert the current date and time to UTC time.

$a = Get-Date $a.IsDaylightSavingTime() $a.ToUniversalTime() #output True Tuesday, June 13, 2006 8:09:19 PM

The first command uses the -Format parameter with a value of "o" to generate a timestamp string.

The second command prepares the timestamp to be used in a directory name. The command replaces the colon characters (:) in the string with dots (.) and saves the result in the $timestamp variable. Replacing the colons prevents the characters that precede each colon from being interpreted as a drive name.

The third command uses the Mkdir function to create a directory with the name in the $timestamp variable. This example shows how to use the Get-Date cmdlet to create a timestamp and how to use the timestamp in or as part of a directory name.

Get-Date -Format o 2012-03-08T10:55:55.6083839-08:00 $timestamp = Get-Date -Format o | foreach {$_ -replace ":", "."} mkdir C:\ps-test\$timestamp # output Directory: C:\ps-test Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 3/8/2012 11:01 AM 2012-03-08T11.00.24.4192623-08.00